<template>
  <div class="app-container">

   <!-- <el-card shadow="never"> -->
    <!-- <div slot="header" style="text-align: center;">门店员工列表</div> -->
           <!-- 搜索黑名单 -->
           <div>
             <el-form>
               <el-row class="rowFormItem">
                <el-col :span="3">
                    <el-input  v-model="keyword" placeholder="姓名/手机号码"/>
                </el-col>
                 <!-- 提交按钮 -->
                 <el-col :span="5" class="clear">
                   <el-form-item style="text-align: center;">
                     <el-button type="primary" size="large" @click="handleSubmit()">检索</el-button>
                     <el-button type="warning" size="large" style="margin-left: 8px" @click="handleReset()">重置</el-button>
                     <el-button type="success" size="large" @click="addmodel">添加</el-button>
                   </el-form-item>
                 </el-col>
               </el-row>
             </el-form>
           </div>

      <div class="tableClass">
        <!-- v-loading="loading" -->
        <el-table :data="formdata" :header-cell-style="{background:'#eef1f6',color:'#606266'}" border style="width: 100%;">
          <el-table-column align="center" prop="id" label="序号" />
          <el-table-column align="center" prop="realname" label="姓名" />
          <el-table-column align="center" prop="phone" label="手机号码" />
          <el-table-column align="center" prop="username" label="账号" />
          <el-table-column align="center" prop="role_name" label="角色">
          <template slot-scope="scope">
              <el-tag v-if="scope.row.role_name !='' " effect="plain">{{scope.row.role_name}}</el-tag>
              <span v-else style="color: red;">暂无角色</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="created_at" label="创建时间" />
          <el-table-column align="center" label="操作" width="230px">
            <template slot-scope="scope">
              <el-button type="warning" size="mini" @click="updateMsg(scope.row.id)">编辑</el-button>
              <el-button type="danger" size="mini" @click="delMsg(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br>
        <!-- 分页 -->
        <div style="text-align: center;">
          <el-pagination background layout="prev, pager, next" @current-change="pageChange" :page-size="pageSize"
            :total="totalusers" />
        </div>
      </div>
 <!--   </el-card> -->

    <!-- 模态款-->
    <div>
      <!-- 添加模态款 -->
      <el-dialog :title="title" :visible.sync="modelMsg">
        <div class="msgDiv">
          <div>
            <el-form ref="form" :model="form" label-width="100px">
              <el-form-item label="序号" v-show="vshow">
                <el-input v-model="form.id" placeholder="序号" disabled></el-input>
              </el-form-item>
              <el-form-item label="账号" :required="true">
                <el-input v-model="form.username" placeholder="请输入账号"></el-input>
              </el-form-item>
              <div v-if="form.id<=0">
                  <el-form-item label="密码" :required="true">
                    <el-input v-model="form.password" placeholder="请输入密码" password></el-input>
                  </el-form-item>
                  <!-- <el-form-item label="再次输入" :required="true">
                    <el-input v-model="form.checkPsw" placeholder="请再次输入密码" password></el-input>
                  </el-form-item> -->
              </div>
              <div v-if="form.id>0">
                  <el-form-item label="修改密码" :required="true" style="text-align: left;">
                    <el-button type="warning" size="small" v-if="updata==false" @click="updata = true">修改密码</el-button>
                    <div v-if="updata==true">
                      <el-input style="width: 65%;margin-right: 5px;"  v-model="form.password" placeholder="不修改无需填写" password></el-input>
                      <el-button type="primary" size="medium"  @click="updata=false;form.password='' ">取消修改</el-button>
                    </div>
                  </el-form-item>
                  <!-- <el-form-item label="再次输入" :required="true">
                    <el-input v-model="form.checkPsw" placeholder="请再次输入密码" password></el-input>
                  </el-form-item> -->
              </div>
              <el-form-item label="姓名" :required="true">
                <el-input v-model="form.realname" placeholder="请输入员工姓名"></el-input>
              </el-form-item>
              <el-form-item label="手机" :required="true">
                <el-input v-model="form.phone" placeholder="请输入员工手机号码"></el-input>
              </el-form-item>
              <el-form-item label="门店ID" v-show="false">
                <el-input v-model="form.merchant_id" placeholder="请输入门店ID"></el-input>
              </el-form-item>
              <el-form-item label="选择角色" :required="true">
                <div style="text-align: left;">
                  <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="checkedRoles" @change="CheckedRolesChange">
                    <el-checkbox v-for="role in rolesList" :key="role.id" :label="role">
                      {{ role.display_name}}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>

              <el-button type="success" @click="addMsg(form)">{{addORupdate}}</el-button>

            </el-form>

          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      merchantIdProp: ''
    },
    watch: {
      merchantIdProp(val){
        if(val){
          this.startpage = 1
          this.keyword = ''
          this.form.merchant_id = val
          this.getMerchantStaffList()
        }
      }
    },
    data() {
      return {
        form: {
          id: "",
          username: "",
          password: "",
          realname:"",
          phone:"",
          merchant_id:"",
          role_id: []
        },
        updata:false,
        checkPsw:"",
        keyword:"",
        title: "",
        vshow: false,
        addORupdate: "",
        modelMsg: false, //模态框
        loading: false, //加载中
        formdata: [],
        //多选框
        rolesList: [],
        checkedRoles: [],
        checkAll: false,
        totalusers: 0, //总页数
        pageSize: 10, //每页几行
        startpage: 1, //起始页
      }
    },
    created() {
       let comeid = this.$route.query.row;
       let comename= this.$route.query.row2;
       window.localStorage.setItem("merchant_id",comeid)
        window.localStorage.setItem("merchant_name",comename)
    },
    mounted() {
      this.form.merchant_id =  window.localStorage.getItem("merchant_id")
      this.getMerchantStaffList()
       this.roleList()
    },
    methods: {

      addmodel() {
        this.modelMsg = true
        this.title = '添加门店员工信息'
        this.addORupdate = "添加",
          this.vshow = false
          this.form.id= "",
          this.form.username= "",
          this.form.password= "",
          // this.checkPsw = "",
          this.form.realname="",
          this.form.phone="",
          this.form.role_id= []
          this.checkedRoles = []
      },
      async addMsg(form) {
        //判断带星号的是否为空
        if ((form.realname && form.username && form.phone) == "") {
           this.$message({
             message: "带星号为必填项，请完善信息！",
             type: "warning"
           })
           return false;
         }
        /* 显示加载中。。。 */
        const loadingOne = this.$loading({
          lock: true,
          text: '保存中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        if (form.id > 0) {
          /* 修改 */
          await this.$api.setMerchantStaff(form).then(res => {
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              this.getMerchantStaffList()
              loadingOne.close()
              this.modelMsg = false
            } else {
              this.modelMsg = true
              loadingOne.close()
            }

          })
        } else {
          /* 添加 */
          await this.$api.setMerchantStaff(form).then(res => {
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              this.getMerchantStaffList()
              loadingOne.close()
              this.modelMsg = false
            } else {
              this.modelMsg = true
              loadingOne.close()
            }

          })
        }

      },
      //修改弹出框
      updateMsg(id) {
        this.modelMsg = true
        this.title = '修改门店员工信息'
        this.addORupdate = "修改",
        this.vshow = true
         this.updata = false
         if(this.updata == false){
           this.form.password = ""
         }
        let dataid = {
          "id":id
        }
        this.$api.getMerchantStaffDetail(dataid).then(res=>{
           let row = res.data.data
           this.form.id = row.user_id
           this.form.username = row.username
           this.form.realname = row.realname
           this.form.phone = row.phone
           this.form.merchant_id = row.merchant_id
           this.form.role_id = row.role_id
           let roleids = []
          roleids = this.form.role_id

           // 判断查询出来的角色权限的长度是否等于所有权限列表，相等则checkAll为true，勾选全选状态，否则勾选已有的几项
           if (roleids.length === this.rolesList.length) {
             this.checkAll = true
             this.handleCheckAllChange(true)
           } else {
             console.log('查询出来的角色权限的长度不等于所有权限列表，并切不勾选全部')
             this.checkAll = false
             this.handleCheckAllChange(false)
             const roleObj = []
             // 根据更新设入的权限id数组并遍历出来和遍历出总权限数组，两个通过冒泡排序方式对比，有相等的id赋值给复选框进行勾选
             for (let j = 0; j < roleids.length; j++) {
               for (let i = 0; i < this.rolesList.length; i++) {
                 const rolesListid = this.rolesList[i].id
                 if (roleids[j] === rolesListid) {
                   roleObj.push(this.rolesList[i])
                   this.CheckedRolesChange(roleObj)
                 }
               }
             }

           }
        })
      }, /* 全选权限 */
      handleCheckAllChange(val) {
        // 判断数组是否有相同数字或字符，有返回true。正则表达式
        Array.prototype.in_array = function(e) {
          var r = new RegExp(',' + e + ',')
          return (r.test(',' + this.join(this.S) + ','))
        }
        /* 三元表达式 */
        this.checkedRoles = val ? this.rolesList : []
        for (let i = 0; i < this.checkedRoles.length; i++) {
          const roleid = this.checkedRoles[i].id
          // 判断权限数组里是否存在相同的ID,为true跳出判断，不能用return，不然会跳出循环。为false追加进权限数组里
          const ss = this.form.role_id.in_array(roleid)
          if (ss === true) {
            continue
          } else {
            this.form.role_id.push(roleid)
          }
        }
        // 假设val为true(全选状态)，就把权限ID追加（push）进role_id[]数组里；否则为空
        this.form.role_id = val ? this.form.role_id : []
      },

      /* 单选 */
      CheckedRolesChange(value) {
        //选中的值
        this.checkedRoles = value
        // 判断假如单选的长度与权限列表长度一致则为true显示勾，否则为false
        const checkedCount = value.length
        this.checkAll = checkedCount === this.rolesList.length
        // 点击单选时，判断选择的权限数组里是否存在这个id,没有则添加，取消钩子要从数组里删除该权限
        const roleid = []
        for (let i = 0; i < value.length; i++) {
          roleid.push(value[i].id)
        }
        this.form.role_id = roleid
      },
      //删除店铺信息
      async delMsg(id) {
        let delid = {
          id: id
        }
        await this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const loadingOne = this.$loading({
            lock: true,
            text: '保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.$api.delMerchantStaff(delid).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            if (res.data.level == "success") {
              loadingOne.close()
              this.getMerchantStaffList()
            } else {
              this.$message.error(res.data.message)
              loadingOne.close()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //搜索
      handleSubmit(){
        this.getMerchantStaffList()
      },
      //重置
      handleReset(){
        this.keyword = ""
      },
      //获取角色列表
       roleList(){
         let params = {
           "page": 1,
           "limit":100000
         }
         this.$api.roleList(params).then(res=>{
           this.rolesList = res.data.data
         })
       },
      //获取分页列表
      getMerchantStaffList() {
        this.loading = true
        let params = {
          "page": this.startpage,
          "limit": this.pageSize,
          "merchant_id": this.form.merchant_id,
          "keyword":this.keyword
        }
        //调用后台提供的接口方法
        this.$api.getMerchantStaffList(params).then(res => {
          if (res.data.level == "success") {
            this.formdata = res.data.data
            this.totalusers = res.data.page_info.total
            this.loading = false
          }else {
            this.$message.error(res.data.message)
             this.loading = false
          }
        })
      },
      //分页 pageChange当前页发生改变触发函数
      async pageChange(page) {
        this.startpage = page
        //调用获取列表的方法
        this.loading = true
        this.getMerchantStaffList()
      },
    }
  }
</script>
<style scoped="scoped">
  /deep/.el-card__header {
    background-color: #409EFF;
    color: whitesmoke;
  }

  /deep/.el-dialog {
    width: 40%;
    margin-top: 5vh !important;
    margin-bottom: 10vh;
  }

  .msgDiv {
    width: 80%;
    margin: auto;
    text-align: center;
  }

  /* model */
  .businessDialog /deep/.el-dialog__title {
    font-size: 26px;
    text-align: center;
    font-weight: bold;
  }

  .businessDialog /deep/.el-dialog__body {
    padding: 30px 50px;
    background-color: #dddddd57;
  }

  .businessDialog /deep/.el-dialog {
    margin-top: 10vh !important;
    width: 33%;
  }

  .businessCss .msgDiv {
    width: 80%;
    margin: auto;
    text-align: center;
  }

  .businessCss /deep/.el-form-item__label {
    font-size: 20px !important;
    text-align: right !important;
  }

  .businessCss /deep/.el-form-item__content {
    font-size: 20px !important;
  }

  /* 任务详细CSS */
  .taskWarp /deep/.el-form-item {
    margin-left: 15px;
  }

  .taskWarpTitle /deep/.el-dialog__title {
    font-size: 22px;
  }

  .taskWarp /deep/.el-form-item__label {
    font-size: 18px;
  }

  .taskCss {
    margin-left: 30px;
    margin-right: 30px;
    font-size: 16px;
    background-color: #dddddd57;
    text-align: left;
    padding: 10px 30px 10px 30px;
    margin-bottom: 10px;
    border-radius: 10px;
  }

  .taskCss span.title {
    font-weight: bold;
  }

  .taskCss span.name {
    color: #e21515eb;
  }

  .taskName {
    font-size: 22px;
    color: #e21515eb;
    background-color: #dddddd57;
    display: inline-block;
    padding: 5px 12px 5px 12px;
    font-weight: bold;
    font-family: serif;
    border-radius: 5px;
  }

  .indentLeft {
    margin-left: 26px;
  }

  .requiredCSS {
    margin-left: 30px;
    margin-right: 30px;
    background-color: #dddddd57;
    border-radius: 10px;
    padding: 10px 30px 10px 30px;
  }

  /deep/.edui-editor-imagescale {
    top: 130px !important;
  }

  /* 图片上传css */
  .avatar-uploader /deep/.el-upload {
    border: 1px dashed #807979;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  /* model */
  .businessDialog /deep/.el-dialog__title {
    font-size: 26px;
    text-align: center;
    font-weight: bold;
  }

  .businessDialog /deep/.el-dialog__body {
    padding: 30px 50px;
    background-color: #dddddd57;
  }

  .businessDialog /deep/.el-dialog {
    margin-top: 10vh !important;
    width: 33%;
  }

  .businessCss .msgDiv {
    width: 80%;
    margin: auto;
    text-align: center;
  }

  /deep/.el-form-item__label {
    padding: 0px 12px 0px 20px;
  }

  .businessCss /deep/.el-form-item__label {
    font-size: 20px !important;
    text-align: right !important;
  }

  .businessCss /deep/.el-form-item__content {
    font-size: 20px !important;
  }

  /* 选择框*/
  .checkboxLeft {
    text-align: left;
    margin-bottom: 15px;
  }

  /deep/.el-checkbox__inner {
    /* width: 18px;
    height: 18px; */
  }

  /deep/.el-checkbox__label {
    font-size: 16px;
  }

  .checkSpan {
    width: 80px;
    line-height: 40px;
    font-size: 16px;
    text-align: right;
    margin-right: 10px;
  }
</style>
